import { useRequest } from 'ahooks'
import { getQuestionListService } from '../services/question'
import { useSearchParams } from 'react-router-dom'
import { LIST_SEARCH_PARAM_KEY, LIST_PAGE_PARAM_KEY, LIST_PAGESIZE_PARAM_KEY, LIST_PAGESIZE } from '../constant'

type OptionType = {
  isStar: boolean
  isDeleted: boolean
}

function useLoadQuestionList(option: Partial<OptionType> = {}) {
  const { isStar = false, isDeleted = false } = option || {}

  const [searchParams] = useSearchParams()

  async function load() {
    const keyword = searchParams.get(LIST_SEARCH_PARAM_KEY) || ''
    const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || '') || 1
    const pageSize = parseInt(searchParams.get(LIST_PAGESIZE_PARAM_KEY) || '') || LIST_PAGESIZE
    const data = await getQuestionListService({ keyword, isStar, isDeleted, page, pageSize })
    return data
  }
  const { data, loading, error } = useRequest(load, {
    refreshDeps: [searchParams]
  })
  return { data, loading, error }
}

export default useLoadQuestionList